import scala.actors.Actor
import scala.actors.Actor._
import scala.collection.mutable.Map
import java.lang.String

case class ExpectUrls(query: String, numberOfUrls : Int)
case class GotPageSize(query: String, url: String, size: Int)
case class FailedToGetPageSize(query: String, url: String)

class State() {
  var nStarted: Int = 0
  var nUrls: Int = 0
  var maxSize: Int = 0
  var maxUrl: String = null
}

/**
 * Actor that listens for results from the other actors to summarize the final result.
 *
 * Will receive ExpectUrls(query, numberOfUrls) first, so it knows how many results to expect
 * for a query.
 *
 * Then it will receive a sequence of GotPageSize or FailedToGetPageSize messages as the
 * results come in. When numberOfUrls for the given query have been received, all results
 * are in.
 */
class SummaryActor extends Actor {

  var queryMap: Map[String, State] = Map.empty[String, State]

  def act() {
    loop {
      react {
        // TODO: Aggregate the results and report on the url with the largest size for a query.

        case ExpectUrls(query, numberOfUrls) => {
          // println("SummaryActor received ExpectUrls('" + query + "', " + numberOfUrls + ")")
          var state : State = queryMap.getOrElse(query, new State())
          state.nStarted += 1
          state.nUrls += numberOfUrls
          queryMap.put(query, state)
        }

        case GotPageSize(query, url, size) => {
          // println("SummaryActor received GotPageSize('" + query + "', '" + url + "', " + size + ")")
          var state : State = queryMap.getOrElse(query, new State())
          if (size > state.maxSize) {
            state.maxSize = size
              state.maxUrl = url
          }
          state.nUrls -= 1
          // println("State.nUrls = " + state.nUrls)
          if (state.nUrls == 0) {
            println("The biggest page for query '" + query + "' is " + state.maxSize + " bytes at '" + state.maxUrl + "'")
          }
        }
        
        case FailedToGetPageSize(query, url) => {
          println("SummaryActor received FailedToGetPageSize('" + query + "', '" + url + "')")
          var state : State = queryMap.getOrElse(query, new State())
          state.nUrls -= 1
          if (state.nUrls == 0) {
            println("The biggest page for query '" + query + "' is " + state.maxSize + " bytes at '" + state.maxUrl + "'")
          }
        }

      }
    }
  }

}
